import React, { Component } from 'react'
import {
  Card,
  Input,
  Form,
  Icon,
  Button,
  Cascader,
  message
} from 'antd'
import LinkButton from '../../components/link-button'
import { reqCategorys, reqAddOrUpdateProduce } from '../../api'
import RichTextEditor from './rich-text-editor'

const {Item} = Form
const { TextArea } = Input;


class ProduceAddUpdate extends Component {

  state = {
    options:[],
  }

  constructor(props) {
    super(props)
    // 创建用来保存ref标识的标签对象的容器
    this.editor = React.createRef()
  }
  
  /**
   * 表单提交
   */
  submit = () => {
    // 进行表单验证
    this.props.form.validateFields(async(error,values)=> {
      if(!error) {
        // 1.收集数据，并封装成produce对象
        const {name, desc,price,categoryIds} = values
        let pCategoryId,categoryId
        if(categoryIds.length===1) {
          pCategoryId = '4'
          categoryId = categoryIds[0]
        } else {
          pCategoryId = categoryIds[0]
          categoryId = categoryIds[1]
        }
        const detail = this.editor.current.getDetail()
        const produce = {name, desc,price,detail, categoryId, pCategoryId}
        console.log('',produce)
        // 如果是更新，需要添加_id
        if(this.isUpdate){
          produce._id = this.produce._id
        }
        // 2.调用接口请求函数去更新/添加
        const result = await reqAddOrUpdateProduce(produce)
        // 3.根据结果显示
        if(result.status === 0) {
          message.success(`${this.isUpdate ? '更新': '添加'}商品成功`)
          this.props.history.goBack()
        } else {
          message.error(`${this.isUpdate ? '更新': '添加'}商品失败`)
        }
      }
    })
  }
  /**
   * 商品价格必须大于0
   */
  validatorPrice = (rule,value,callback) => {
    if(value*1 > 0) {
      callback() // 验证通过
    } else {
      callback('输入的价格必须大于0') // 验证不通过
    }
  }

  initOptions = async (categorys) => {
    // 根据categorys生成option数组
    const options = categorys.map(c => ({
        value: c._id,
        label: c.name,
        isLeaf: false,  // 显示“>”
    }))

    // 如果是一个二级分类商品的更新
    // const {isUpdate, produce} = this
    // const {pCategoryId, categoryId} = produce
    // if(isUpdate && pCategoryId !== '4') {
    //   // 获取对应的二级分类列表
    //   const subCategorys = await this.getCategory(pCategoryId)
    //   // 生成二级下拉列表options
    //   const childOptions = subCategorys.map(c=>({
    //     value: c._id,
    //     label: c.name,
    //     isLeaf: true,  // 隐藏“>”
    //   }))
    //   // 找到当前商品对应的一级option对象
    //   const targetOption = options.find(option => option.value == pCategoryId)
    //   // 关联到当前options上
    //   targetOption.children = childOptions
    // }
    // 更新options状态
    this.setState({
      options
    })
  }
  /**
   * 异步获取一级/二级分类列表，并显示
   */

  getCategory = async (parentId) => {
    const result = await reqCategorys(parentId)
    if(result.status === 0) {
      const categorys = result.data
      if(parentId === '4'){ // 一级列表
        this.initOptions(categorys)
      } else { // 二级列表
        return categorys // 返回二级列表 ===>value的值为categorys
      }
    }
  }

  loadData = async selectedOptions => {
    // 得到选择的option对象
    const targetOption = selectedOptions[0];
    // 显示loading
    targetOption.loading = true;

    // 根据选中的分类，请求获取二级分类列表
    const subCategorys = await this.getCategory(targetOption.value)
    targetOption.loading = false;
    if (subCategorys && subCategorys.length>0) {
      const childOptions = subCategorys.map(c=>({
        value: c._id,
        label: c.name,
        isLeaf: true,  // 隐藏“>”
      }))
      // 关联到当前options上
      targetOption.children = childOptions
    } else {
       // 显示loading
    targetOption.isLeaf = true;
    }
    // 更新options状态
    this.setState({
      options: [...this.state.options],
    })
  }

  componentDidMount() {
    this.getCategory('4')
  }

  UNSAFE_componentWillMount() {
    // 取出携带的state
    const produce = this.props.location.state // 如果是添加没值，否则有值
    console.log('@produce',produce)
    // 保存是否是更新的标识
    this.isUpdate = !!produce  // !!表示强制转换为布尔值
    // 保存商品，如果没有，保存的是一个{}
    this.produce = produce || {}
  }
 
  render() {

    const {isUpdate,produce} = this
    const {pCategoryId,categoryId, detail} = produce
    // 用来接收级联分类ID的数组
    const categoryIds = []
    if(isUpdate) {
      // 商品一级分类
      if(pCategoryId === '4') {
        categoryIds.push(categoryId)
      } else {
        // 商品二级分类
        categoryIds.push(pCategoryId)
        categoryIds.push(categoryId)
      }
    }

    const title = (
      <span>
        <LinkButton onClick={() => this.props.history.goBack()}>
          <Icon 
            type='arrow-left'
            style={{color: 'green', marginRight: 5,fontSize: 20}}
          />
        </LinkButton>
        <span>{isUpdate ? '修改商品' : '添加商品'}</span>
      </span>
    )

    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 2 },
      wrapperCol: { span: 4 },
    }

    return (
      <Card title={title}>
        <Form {...formItemLayout}>
          <Item label="商品名称">
            {
              getFieldDecorator('name',{
                initialValue: produce.name,
                rules: [
                  {
                    required: true,
                    message: '请输入商品名称',
                  },
                ],
              })(
                <Input placeholder="请输入商品名称" />
              )
            }
          </Item>
          <Item label="商品描述">
            {
              getFieldDecorator('desc',{
                initialValue: produce.desc,
                rules: [
                  {
                    required: true,
                    message: '请输入商品描述',
                  },
                ],
              })(
                <TextArea
                  placeholder="请输入商品描述"
                  autosize 
                />
              )
            }
          </Item>
          <Item label="商品价格">
            {
              getFieldDecorator('price',{
                initialValue: produce.price,
                rules: [
                  {
                    required: true,
                    message: '请输入商品价格',
                  },
                  {validator: this.validatorPrice}
                ],
              })(
                <Input placeholder="请输入商品价格" addonAfter='元' />
              )
            }
          </Item>
          <Item label="商品分类">
            {
              getFieldDecorator('categoryIds',{
                initialValue: categoryIds,
                rules: [
                  {
                    required: true,
                    message: '必须选择分类商品',
                  }
                ]
              })(
                <Cascader options={this.state.options} loadData={this.loadData} />
              )
            }
          </Item>
          <Item label="商品图片">
            
          </Item>
          <Item label="商品详情" labelCol={{span: 2}} wrapperCol={{span: 15}}>
            <RichTextEditor ref={this.editor} detail={detail} />
          </Item>
          <Item>
            <Button type="primary" onClick={this.submit}>提交</Button>
          </Item>
        </Form>
      </Card>
    )
  }
}

export default Form.create()(ProduceAddUpdate)
